package com.lay.http.core;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by Administrator on 2019-11-04.
 */

public class DownloadResponse extends ResponseBody {

    @Override
    public void handle(InputStream inputStream, ResponseBody.ProcessListener listener) {
        try {
            final int size = 1024 * 10;
            byte[] buffer = new byte[size];
            int length = 0;
            int l = 0;
            int offset = 0;
            boolean result = true;
            while ((l = inputStream.read(buffer, offset, size - offset)) != -1) {
                length += l;
                offset += l;
                if(offset >= size) {
                    byte[] data = new byte[offset];
                    System.arraycopy(buffer, 0, data, 0, offset);
                    result = listener.onProcess(data, length);
                    offset = 0;
                }
                if(!result) {
                    break;
                }
            }
            if(offset != 0){
                byte[] data = new byte[offset];
                System.arraycopy(buffer, 0, data, 0, offset);
                listener.onProcess(data, length);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
